package com.y3k.service;

import java.util.List;

import org.apache.log4j.Logger;

import com.y3k.dao.QueryDao;
import com.y3k.model.CustomFilter;
import com.y3k.model.Filter;

public class QueryService {

	public static final Logger log = Logger.getLogger(QueryService.class);

	private List<Filter> filters;

	private final QueryDao dao = new QueryDao();

	public List<Filter> getFiltros() {
		return filters;
	}

	public void setFiltros(List<Filter> filters) {
		this.filters = filters;
	}

	public QueryService() {

	}

	public List<Object> execute(String query, List<Filter> filters, CustomFilter customFilter) throws ServiceException {
		try {
			query = query.replaceAll("(VALUE)", customFilter.getValue());
			query = query.replaceAll("(CATEGORY)", customFilter.getCategory());
			query = query.replaceAll("(REFRESH_TIME)", customFilter.getRefreshTime());
			query = replaceFilters(query, filters);
			return dao.execute(query);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("Error ejecutando : " + query, e);
		}
	}

	private static String replaceFilters(String query, List<Filter> filters) {
		for (Filter filter : filters) {		
			if (!"".equals(filter.getSelected())) {
				query = query.replaceAll(filter.getFilterName(), mask(filter.getSelected()));
			} else {
				query = query.replaceAll(filter.getFilterName(), filter.getQuery());
			}
		}
		return query;
	}

	private static String mask(String filtro) {
		String maskedFiltro = new String();
		String[] data = filtro.split(",");

		for (int i = 0; i < data.length; i++) {
			maskedFiltro += "'" + data[i] + "',";
		}

		return maskedFiltro.substring(0, maskedFiltro.length() - 1);
	}
}